from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render, redirect

from myapp import models

# Create your views here.
from myapp.utils import getPublicData, getHomeData, getSelfInfoData, getTableData, getSalaryCharData, \
    getCompanyCharData, getEducationalCharData, getCompanyStatusCharData, getCityCharData, getHistoryData, \
    getCompanyTagsData
from myapp.utils.error import errorResponse
from myapp.utils.getHomeData import getUserCreateTime, getLatestUserInfo


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username', '')
        pwd = request.POST.get('password', '')
        print(f'----- user: {username}, pwd: {pwd}')
        if not username or not pwd:
            return HttpResponse('账号或密码不正确！')

        pwd = getPublicData.md5Data(pwd)
        user = models.Users.objects.filter(username=username, password=pwd).first()
        if not user: return errorResponse(request, '账号或密码不正确！')

        request.session['username'] = user.username
        return redirect('home')

def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        username = request.POST.get('username', '')
        pwd = request.POST.get('password', '')
        checkPwd = request.POST.get('checkPassword', '')
        print('---------------------', username, pwd, checkPwd)

        # 判断用户是否已存在
        user = models.Users.objects.filter(username=username).first()
        if user: return errorResponse(request, '该账号已被注册！')
        # 判断两次密码是否一致
        if pwd != checkPwd: return errorResponse(request, '两次密码输入不一致！')

        pwd = getPublicData.md5Data(pwd)
        # 新建用户、密码加密入库
        models.Users.objects.create(
            username=username,
            password=pwd,
        )
        return redirect('login')


def logOut(request):
    request.session.clear()
    return redirect('login')


def updateSelfInfo(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()

    educationalList, experienceList, jobList = getSelfInfoData.getPageData()

    if request.method == 'POST':
        getSelfInfoData.changeData(request)
        user = models.Users.objects.filter(username=username).first()

    return render(request, 'selfInfo.html', {
        'userInfo': user if user else {},
        'educationals': educationalList,
        'experiences': experienceList,
        'jobs': jobList
    })


def changePassword(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()
    if not user: return errorResponse(request, '用户信息不存在！')

    if request.method == 'POST':
        oldPassword = request.POST.get('oldPassword', '')
        newPassword = request.POST.get('newPassword', '')
        checkPassword = request.POST.get('checkPassword', '')
        print(f'-- old: {oldPassword}, new: {newPassword}')

        if not oldPassword or not newPassword or not checkPassword:
            return errorResponse(request, '请输入正确信息！')

        if user.password != getPublicData.md5Data(oldPassword): return errorResponse(request, '旧密码输入不正确！')
        if newPassword != checkPassword: return errorResponse(request, '两次密码输入不一致！')

        # user.password = getPublicData.md5Data(newPassword)
        # user.save()

    return render(request, 'changePassword.html', {
        'userInfo': user
    })


def home(request):
    username = request.session.get('username')
    print(f'----- 用户信息: {username}')
    user = models.Users.objects.filter(username=username).first()
    if not user: return errorResponse(request, '用户信息异常！')

    year, month, day = getHomeData.getNowTime()

    pageData = getHomeData.getPageData()

    createTimeData = getUserCreateTime()

    userData = getLatestUserInfo()

    jobData = getHomeData.getJobsInfo()

    return render(request, 'home.html', {
        'userInfo': user,
        'dateInfo': {'year': year, 'month': month, 'day': day},
        'createTimeData': createTimeData,
        'users': userData,
        'jobData': jobData,
        'pageData': pageData,
    })


def tableData(request):
    currentPage = int(request.GET.get('page', 1))
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()

    tableData = getTableData.getPageData()
    # print(len(tableData))

    # 分页器
    paginator = Paginator(tableData, 10)
    pageData = paginator.page(currentPage)

    # 构造页码数
    pageRange = []
    visibleNumber = 10
    minPage = int(currentPage - visibleNumber / 10)
    if minPage < 1: minPage = 1
    maxPage = minPage + visibleNumber
    # print(f"----- max: {maxPage}")
    if maxPage > paginator.num_pages: maxPage = paginator.num_pages

    for i in range(minPage, maxPage):
        pageRange.append(i)
    # print(pageRange, paginator.num_pages)

    return render(request, 'tableData.html', {
        'userInfo': user,
        'pageData': pageData,
        'pageRange': pageRange,
        'paginator': paginator,
    })


def historyData(request):
    username = request.session.get('username')
    user = models.Users.objects.filter(username=username).first()
    currentPage = int(request.GET.get('page', 1))

    tableData = getHistoryData.getTableData(user)

    # 分页器
    paginator = Paginator(tableData, 10)
    pageData = paginator.page(currentPage)

    # 构造页码数
    pageRange = []
    visibleNumber = 10
    minPage = int(currentPage - visibleNumber / 10)
    if minPage < 1: minPage = 1
    maxPage = minPage + visibleNumber
    # print(f"----- max: {maxPage}")
    if maxPage > paginator.num_pages: maxPage = paginator.num_pages

    for i in range(minPage, maxPage):
        pageRange.append(i)

    return render(request, 'historyTableData.html', {
        'userInfo': user,
        'pageData': pageData,
        'pageRange': pageRange,
        'paginator': paginator,
    })

def addHistory(request, jobId):
    username = request.session.get('username')
    user = models.Users.objects.filter(username=username).first()
    getHistoryData.addHistoryData(user, jobId)

    return redirect('historyData')

def removeHistory(request, hisId):
    getHistoryData.removeHistoryData(hisId)

    return redirect('historyData')



def salaryChar(request):
    username = request.session.get('username')
    user = models.Users.objects.filter(username=username).first()

    educationals, experiences = getSalaryCharData.getPageData()
    defaultEducational = '不限'
    defaultExperience = '不限'
    if request.GET.get('educational'): defaultEducational = request.GET.get('educational')
    if request.GET.get('experience'): defaultExperience = request.GET.get('experience')

    salaryList, barData, legends = getSalaryCharData.getBarData(defaultEducational, defaultExperience)

    pieData = getSalaryCharData.getPieData()

    funnelData = getSalaryCharData.getFunnelData()

    return render(request, 'salaryChar.html', {
        'userInfo': user,
        'educationals': educationals,
        'defaultEducational': defaultEducational,
        'experiences': experiences,
        'defaultExperience': defaultExperience,
        'salaryList': salaryList,
        'barData': barData,
        'legends': legends,
        'pieData': pieData,
        'funnelData': funnelData,
    })


def companyChar(request):
    username = request.session.get('username')
    user = models.Users.objects.filter(username=username).first()

    typeData = getCompanyCharData.getPageData()
    defaultType = 'all'
    if request.GET.get('type'): defaultType = request.GET['type']

    barRowData, barColumnData = getCompanyCharData.getBarData(defaultType)

    pieData = getCompanyCharData.getPieData(defaultType)
    # print(pieData)

    areaData, areaLegend = getCompanyCharData.getAreaData(defaultType)

    return render(request, 'companyChar.html', {
        'userInfo': user,
        'typeData': typeData,
        'defaultType': defaultType,
        'barRowData': barRowData,
        'barColumnData': barColumnData,
        'pieData': pieData,
        'areaData': areaData,
        'areaLegend': areaLegend,
    })


def companyTagsChar(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()
    # 耗时有点大
    hasTagsCloud, hasTitleCloud = getCompanyTagsData.getPageData()

    return render(request, 'companyTagsChar.html', {
        'userInfo': user,
        # 'hasTagsCloud': hasTagsCloud,
        # 'hasTitleCloud': hasTitleCloud,
    })


def educationalChar(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()

    defaultEducational = '不限'
    if request.GET.get('educational'): defaultEducational = request.GET['educational']

    educationals = getEducationalCharData.getPageData()

    expRowData, expColumnSalary, expColumnPeople, hasEmpty = getEducationalCharData.getExperienceData(defaultEducational)

    eduRowData, eduColumnData = getEducationalCharData.getEducationalData()

    return render(request, 'educationalChar.html', {
        'userInfo': user,
        'educationals': educationals,
        'defaultEducational': defaultEducational,
        'expRowData': expRowData,
        'expColumnSalary': expColumnSalary,
        'expColumnPeople': expColumnPeople,
        'hasEmpty': hasEmpty,
        'eduRowData': eduRowData,
        'eduColumnData': eduColumnData
    })



def companyStatusChar(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()

    defaultJob = '不限'
    if request.GET.get('job'): defaultJob = request.GET['job']

    jobs = getCompanyStatusCharData.getPageData()

    barRowTagData, barColumnTagData = getCompanyStatusCharData.getBarTagData(defaultJob)

    pieStatusData = getCompanyStatusCharData.getPieStatusData(defaultJob)

    return render(request, 'companyStatusChar.html', {
        'userInfo': user,
        'defaultJob': defaultJob,
        'jobs': jobs,
        'barRowTagData': barRowTagData,
        'barColumnTagData': barColumnTagData,
        'pieStatusData': pieStatusData,
    })



def addressChar(request):
    username = request.session.get('username', '')
    user = models.Users.objects.filter(username=username).first()

    defaultCity = '北京'
    if request.GET.get('city'): defaultCity = request.GET['city']

    hotCitys = getCityCharData.getPageData()

    lineRowSalaryData, lineColumnSalaryData = getCityCharData.getSalaryData(defaultCity)

    piePeopleData = getCityCharData.getPeopleData(defaultCity)

    funnelEducationalData = getCityCharData.getEducationalData(defaultCity)

    pieDistData = getCityCharData.getDistData(defaultCity)

    # hasTagCloud, tagCloudImage = getCityCharData.getCompanyTagsData(defaultCity)
    tagCloudImage = '584149.png'

    return render(request, 'cityChar.html', {
        'userInfo': user,
        'defaultCity': defaultCity,
        'citys': hotCitys,
        'lineRowSalaryData': lineRowSalaryData,
        'lineColumnSalaryData': lineColumnSalaryData,
        'piePeopleData': piePeopleData,
        'funnelEducationalData': funnelEducationalData,
        'pieDistData': pieDistData,
        # 'hasTagCloud': hasTagCloud,
        'tagCloudImage': tagCloudImage,
    })
